<?
/**
 * @version        $Id: function.php 2014年8月20日Z yeshili $
 * @package        YeshiliCMS.Admin
 * @copyright      Copyright (c) 2014 - 2050, YeshiliCMS, Inc.
 * @license        http://help.****.com/YeshiliCMS/help.html
 * @link           http://www.****.com
 */
//获取下拉菜单类别
function getCategorySelect($tablename,$select_id=0,$id = 0,$level = 0){
	global $db;
	$category_arr = $db->getList (get_sql( "SELECT * FROM {pre}$tablename WHERE fid = " . $id . " order by rank" ));
	for($lev = 0; $lev < $level * 2 - 1; $lev ++) {
		$level_nbsp .= "&nbsp;";
	}
	if ($level++)
		$level_nbsp .= "┝";
	foreach ( $category_arr as $category ) {
		$id = $category ['id'];
		$fid = $category ['fid'];
		$name = $category ['name'];
		$selected = $select_id==$id?'selected':'';
		echo "<option value=\"".$id."\" ".$selected.">".$level_nbsp . " " . $name."</option>\n";
		getCategorySelect ($tablename,$select_id, $id, $level );
	}
}

//获取下拉菜单类别
function getActionSelect($tablename,$select_id=0,$id = 0,$type=0){
	global $db;
	$category_arr = $db->getList (get_sql( "SELECT * FROM {pre}$tablename WHERE fid = " . $id . " order by rank" ));
	foreach ( $category_arr as $category ) {
		$id = $category ['id'];
		$fid = $category ['fid'];
		$title = $category ['title'];
		$selected = $select_id==$id?'selected':'';
		echo "<option value=\"".$id."\" ".$selected.">" . $title."</option>\n";
		if($type==1){getActionSelect ($tablename,$select_id, $id);}
	}
}
//获取下拉菜单类别
function getSelect($tablename,$id = 0){
	global $db;
	$category = $db->getOneRow(get_sql( "SELECT name FROM {pre}$tablename WHERE id = ".$id));
	echo $category ['name'];
}

//获取传递参数
function getvar($var){
	$result = isset($_GET[$var])?$_GET[$var]:$_POST[$var];
	$result = addslashes(trim($result));
	return $result;
}

//获取翻页变量
function getpage($var1,$str1,$var2,$str2,$var3,$str3){
	if($var1<>'' or $str1<>''){$v1=$var1.'='.$str1."&";}
	if($var2<>'' or $str2<>''){$v2=$var2.'='.$str2."&";}
	if($var3<>'' or $str3<>''){$v3=$var3.'='.$str3;}
	return $v1.$v2.$v3;
}

//后台用分页
function page($sqlstr,$pagesize,$url,$page){
	global $db;
	$p = empty($page)?1:$page;
	$totle_nums=$db->getRowsNum($sqlstr);
	$page_nums=ceil($totle_nums/$pagesize);
	$pre_page=$page-1;
	$next_page=$page+1;
	$var_temp= '<div class=page><span><strong>'.$pagesize.'/'.$totle_nums.'</strong></span>';
	   //获得上一页和下一页的链接
        if($page != 1)
        {
			$var_temp.='<a href='.$url.'=1><<</a><a href='.$url.'='.$pre_page.'><</a>';
        }
        else
        {
            $var_temp.='<a href="#"><<</a>';
        }
	   //获得数字链接
        $total_list = $pagesize+1;
        if($page >= $total_list)
        {
            $i = $page-$pagesize;
            $total_list = $page+$pagesize;
            if($total_list>$page_nums)
            {
                $total_list=$page_nums;
            }
        }
        else
        {
            $i=1;
            if($total_list>$page_nums)
            {
                $total_list=$page_nums;
            }
        }
		for($i;$i<$total_list+1;$i++){
			if($i==$p){
				$var_temp.= '<a href="#" class=in>'.$i.'</a>';
			}else{
				$var_temp.= '<a href='.$url.'='.$i.'>'.$i.'</a>';
			}
		}
	  if($page!=$page_nums && $page_nums>1)
        {
            $var_temp.= '<a href='.$url.'='.$next_page.'>></a><a href='.$url.'='.$page_nums.'>>></a>';
        }
        else
        {
           $var_temp.= '<a href="#">>></a>';
        }
	   $var_temp.='</div>';
	echo $var_temp;
}



//处理SQL中表名前缀{pre}
function get_sql($sql_str){
	$sql_temp = str_replace('{pre}',$GLOBALS[dbprefix],$sql_str);
	return $sql_temp;
}
//判断是不是超级管理员/系统管理员
function get_rankadmin($id){
	global $db;
	$list = $db->getonerow(get_sql("select rankadmin from {pre}admin where id=".$id));
	if ($list['rankadmin']==1){
		return '超级管理员';
	}elseif($list['rankadmin']==2){
		return '普通管理员';
	}else{
	    exits();		
	}
}

//判断权限
function get_rank($id){
	global $db;
	$list = $db->getonerow(get_sql("select rankadmin from {pre}admin where id=".$id));
	if ($list['rankadmin']!=1){
		 echo "<script>alert('你没有该权限使用权!');history.go(-1);</script>";
		 exit();
	}
}

//获取用户发布信息
function get_usercontent($rankadmin){
	if($rankadmin==2){return "where mid=".$_SESSION['id'];}
	if($rankadmin==3){return "where uid=".$_SESSION['id'];}
}

//获取表任意字段
function get_field($table,$field,$type,$id){
	global $db;
	$list = $db->getOneRow(get_sql("select {$field} from {pre}{$table} where {$type}='".$id."'"));
	return  $list[$field];
}

//获取栏目字段
function get_action($fid){
	global $db;
	if($fid==0){
		return "<samp style='font-weight:bold;'>顶级栏目</samp>";
		}else{
		$list = $db->getOneRow(get_sql("select title from {pre}action where id='".$fid."'"));
		return  "<samp style='color:#f30;'>".$list['title']."</samp>";	
	}
}

//输出表任意字段
function echo_field($table,$field,$type,$id){
	global $db;
	$list = $db->getOneRow(get_sql("select {$field} from {pre}{$table} where {$type}='".$id."'"));
	echo $list[$field];
}

//删除id附件
function get_delfile0($id){
	global $db;
	$list = $db->getonerow(get_sql("select url from {pre}files where id=".$id));
	@unlink($_SERVER['DOCUMENT_ROOT'].$list['url']);
}
//删除文章附件
function get_delfile1($typeid,$id){
	global $db;
	$list = $db->getlist(get_sql("select url from {pre}files where ".$typeid."=".$id));
	foreach($list as $v){
	@unlink($_SERVER['DOCUMENT_ROOT'].$v['url']);
	}
	$db->delete($GLOBALS[dbprefix].'files',$typeid.'='.$id);
}

//获取附件名称
function get_namefile($title,$url){
	if($title<>''){
		 return "<a href='".$url."' class='fancybox'>".$title."</a>";
		}else
		{
		 return "<a href='".$url."' class='fancybox'>".$url."</a>";
		}
}
/*function get_namefile($table,$field,$id,$url){
	global $db;
	$list = $db->getonerow(get_sql("select ".$field." from {pre}".$table." where id=".$id));
	if($list[$field]<>''){
		 return "<a href='".$url."' class='fancybox'>".$list[$field]."</a>";
		}else
		{
		 return "<a href='".$url."' class='fancybox'>".$url."</a>";
		}
}*/

//获取附件类型图标
function get_fileicon($type){
	$dir=$_SERVER['DOCUMENT_ROOT'].'/inc/kindeditor/img/'.$type.'.gif';
	if(is_file($dir)){
	 return '<img src="../inc/kindeditor/img/'.$type.'.gif" alt="'.$type.'"/>';}
	else
	{
	 return $type;
	}
}

//更新文章附件id
function get_upfiles($table,$uid,$typeid,$title,$id){
	global $db;
	if($id==''){if($_SESSION['rankadmin']==3){$wh="uid=".$uid;}else{$wh="mid=".$uid;}}else{$wh="id=".$id;}
	$list0 = $db->getonerow(get_sql("select id from {pre}".$table." where {$wh} order by datetime desc"));
	$list1 = $db->getonerow(get_sql("select mate from {pre}files where uid=".$uid." and ".$typeid."=0 and mate<>1 order by datetime desc"));
	if($list1['mate']==date("Y-m-d H")){
		$record = array(
		$typeid		=>$list0['id'],
		'title'		=>$title,
		'mate'		=>1
	     );
		$db->update($GLOBALS[dbprefix].'files',$record,'uid='.$uid.' and '.$typeid.'=0 and mate<>1');
	}else
	{
	 	$db->update($GLOBALS[dbprefix].'files',array('title'=>$title),$typeid.'='.$list0['id'].' and mate=1');
	}
}

//记录日记
function get_record($title,$type){
	global $db,$cfg_record;
	if($cfg_record=="Y"){
	  $array=array('add'=>"【添加】",'mod'=>"【修改】",'del'=>"【删除】",'kan'=>"【访问】",'yidong'=>"【移动】",'fasong'=>"【发送】",'dayin'=>"【打印】",'genzong'=>"【跟踪】",'export'=>"【导出数据】",'import'=>"【导入数据】");
	  $bt = $array[$type];
	  $record = array(
		  'uid'		    =>$_SESSION['id'],
		  'username'	=>$_SESSION['username'],
		  'title'		=>$bt.$title,
		  'ip'		    =>get_userip(),
		  'datetime'	=>date("y-m-d H-i-s")
	  );
	  $db->insert($GLOBALS[dbprefix].'record',$record);
	}
}
/*email邮件发送*/
function get_send($id,$email,$type){
require_once 'mail.class.php';
global $db,$cfg_sendmail_bysmtp,$cfg_smtp_server,$cfg_smtp_port,$cfg_smtp_email,$cfg_smtp_user,$cfg_smtp_pass;
if($cfg_sendmail_bysmtp == 'Y' and $cfg_smtp_server != '' and $cfg_smtp_email != '' and $cfg_smtp_user != '' and $cfg_smtp_pass !='' and $cfg_smtp_port !=''){
$row=$db->getonerow(get_sql("select id,title,content from {pre}email where id=".$id));
if($row){
$MailServer = $cfg_smtp_server;
$MailPort   = $cfg_smtp_port;
$MailId     = $cfg_smtp_user;
$MailPw     = $cfg_smtp_pass;
$MailName   = $cfg_smtp_email;
$Title      = $row['title'];
$Content    = $row['content'];
$Email      = $email;
$MailType = 'HTML';
$smtp = new smtp($MailServer,$MailPort,true,$MailId,$MailPw);
$smtp->debug = false;
if($type=='fsend'){
$smtp->sendmail($Email,$MailName ,$MailId,$Title,$Content,$MailType,"UTF-8");	
}
else{
if($smtp->sendmail($Email,$MailName ,$MailId,$Title,$Content,$MailType,"UTF-8")=='2')
{
echo "<script>alert('发送失败,请检查SMTP服务器是否配置正确或者用户邮箱正确!');history.go(-1);</script>";	
exit();	
}
}
}else{
echo "<script>alert('模版参数出错!');history.go(-1);</script>";	
exit();	
}}else{
echo "<script>alert('邮箱SMTP服务器参数未开启或者未配置!');history.go(-1);</script>";
exit();	
}	
}
/*导入execel数据*/
function sava_data($array,$userid){  
    global $db;  
    $count =0;    
    $total =0;
    foreach( $array as $tmp){
		 if($userid==0){$mid=get_field('admin','id','username',$tmp[1]);if($mid==''){$mid=$_SESSION['id'];}}else{$mid=$userid;}
		 $area=get_field('area','id','name',$tmp[12]);
		 $industry=get_field('industry','id','name',$tmp[13]);
		 $record = array(
		  'mid'		=>$mid,
		  'uid'		=>$mid,
		  'name'	=>$tmp[2],
		  'job'		=>$tmp[3],
		  'tel'		=>$tmp[4],
		  'mobile'	=>$tmp[5],
		  'qq'		=>$tmp[6],
		  'weixin'	=>$tmp[7],
		  'email'	=>$tmp[8],
		  'fax'		=>$tmp[9],
		  'httpurl'	=>$tmp[10],
		  'address'	=>$tmp[11],
		  'area'	=>$area,
		  'industry'=>$industry,
		  'services'=>'0',
		  'rank'=>'0',
		  'datetime'=>date("Y-m-d H-i-s")
		  );
		  $Isql = $db->getonerow(get_sql("Select email from {pre}customer where email='".$tmp[8]."'"));
		  if(!$Isql){
			$db->insert($GLOBALS[dbprefix].'customer',$record);
			$count++;
		  }
		  $total++;
    }
    echo "<script>alert('共有".$total."条数据,成功导入".$count."条数据,失败或者已存在".($total-$count)."条数据！');history.go(-1);</script>";
    
}

//getip
function get_userip(){
	$user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
	$user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"]; 
	return $user_IP;
}
//截取字符
function utf_substr($str,$len){
	for($i=0;$i<$len;$i++){
		$temp_str=substr($str,0,1);
		if(ord($temp_str) > 127){
			$i++;
			if($i<$len){
				$new_str[]=substr($str,0,3);
				$str=substr($str,3);
			}
		}else{
			$new_str[]=substr($str,0,1);
			$str=substr($str,1);
		}
	}
	return join($new_str);
}
//保存远程图片到本地
function get_remote_img($str){
	define ( ROOT , dirname ( dirname ( dirname ( $_SERVER['SCRIPT_FILENAME'] ) ) ) . '/' );
	$body = stripslashes(stripslashes($str));
	$img_array = array();
	preg_match_all("/(src|SRC)=[\"|'| ]{0,}(http:\/\/(.*)\.(gif|jpg|jpeg|bmp|png))/isU",$body,$img_array);
	$img_array = array_unique($img_array[2]);
	set_time_limit(0);
	$imgUrl = "upload/".strftime("%Y%m%d",time());
	$imgPath = ROOT.$imgUrl;
	$milliSecond = strftime("%H%M%S",time());
	if(!is_dir($imgPath)) @mkdir($imgPath,0777);
	foreach($img_array as $key =>$value)
	{
			$value = trim($value);
			$get_file = @file_get_contents($value);
			$rndFileName = $imgPath."/".$milliSecond.$key.".".substr($value,-3,3);
			$fileurl = $imgUrl."/".$milliSecond.$key.".".substr($value,-3,3);
			if($get_file)
			{
					$fp = @fopen($rndFileName,"w");
					@fwrite($fp,$get_file);
					@fclose($fp);
			}
			$body = ereg_replace($value,$fileurl,$body);
	}
	$body = addslashes($body);
	return $body;
}
//替换HTML字符，用于htmlspecialchars之后出现的&ldquo;&rdquo;&lsquo;&rsquo;&nbsp;等
function get_html_replace($str){
	preg_match_all("/&(.*?);/",$str,$str_array);
	$str_array = array_unique($str_array[0]);
	foreach($str_array as $key => $value){
		$str = str_replace($value,"",$str);
	}
	return $str;
}
//把内容的空格替换成“_”下划线
function get_nbsp($str){
	$temp = str_replace(" ","_",trim($str));
	return $temp;
}
//获取指定表的指定字段
function get_table_row($tablename,$id,$str){
	global $db;
	$sql = get_sql("select id,$str from {pre}$tablename where id=".$id);
	$list = $db->getonerow($sql);
	return $list[$str];
}
//获取服务复选框列表
function get_services_list($checkbox_name,$act,$services){
	global $db;
	$sql = get_sql("select id,fid,name,rank from {pre}services order by id");
	$s_list = $db->getlist($sql);
	foreach($s_list as $key=>$list){
		if($list['fid'] == 0){$temp = $temp."<br>";}
		if(isset($services) || strlen($services)>2 || $services > 0 ){
			$temp_services = get_services_id($services);
			$s_array = split(",",$temp_services);
			if(in_array($list['id'],$s_array)){
				$temp .= "<input type=\"checkbox\" name=\"".$checkbox_name."[]\" id=\"service".$checkbox_name."\" value=\"".$list['id']."\" onclick=\"".$act."(".$list['id'].");\" checked=\"checked\" />".$list['name'];
			}else{
				$temp .= "<input type=\"checkbox\" name=\"".$checkbox_name."[]\" id=\"service".$checkbox_name."\" value=\"".$list['id']."\" onclick=\"".$act."(".$list['id'].");\" />".$list['name'];
			}
		}else{
			$temp .= "<input type=\"checkbox\" name=\"".$checkbox_name."[]\" id=\"service".$checkbox_name."\" value=\"".$list['id']."\" onclick=\"".$act."(".$list['id'].");\" />".$list['name'];
		}
	}
	$temp = substr($temp,4,strlen($temp));
	return $temp;
}

//获取服务复选框列表
function get_checkbox_list($checkbox_name,$services){
	global $db;
	$sql = get_sql("select id,fid,name,rank from {pre}services order by id");
	$s_list = $db->getlist($sql);
	foreach($s_list as $key=>$list){
		if($list['fid'] == 0){$temp = $temp."<br>";}
		if(isset($services) || strlen($services)>2 || $services > 0 ){
			$temp_services = get_services_id($services);
			$s_array = split(",",$temp_services);
			if(in_array($list['id'],$s_array)){
				$temp .= "<input type=\"checkbox\" name=\"".$checkbox_name."[]\" id=\"service".$checkbox_name."\" value=\"".$list['id']."\" onclick=\"".$act."(".$list['id'].");\" checked=\"checked\" />".$list['name'];
			}
		}
	}
	$temp = substr($temp,4,strlen($temp));
	return $temp;
}
//获取服务内容,用于客户列表中
function get_admin_services($str){
	$str_array = split("\|",$str);
	foreach($str_array as $str_list){
		$str_list_array = split(",",$str_list);
		$temp_str = get_table_row("services",$str_list_array[0],"name");
		$temp = empty($temp) ? $temp_str : $temp.",".$temp_str;
	}
	return $temp;
}
//获取服务内容,用于客户信息修改中
function get_services_id($str){
	$str_array = split("\|",$str);
	foreach($str_array as $str_list){
		$str_list_array = split(",",$str_list);
		//$temp_str = get_table_row("services",$str_list_array[0],"name");
		$temp = empty($temp) ? $str_list_array[0] : $temp.",".$str_list_array[0];
	}
	return $temp;
}
//获取服务内容里的指定字段，主要是查询时间
function get_services_row($service,$row,$id){
	$str_array = split("\|",$service);
	foreach($str_array as $str_list){
		$str_list_array = split(",",$str_list);
		if($str_list_array[0] == $id){
			return $str_list_array[$row];
		}
	}
}

//获取用户登录信息
function sessionlogin()
{
	if($_SESSION['username']<>'' and $_SESSION['password']<>'' and $_SESSION['id']<>'' and $_SESSION['rankadmin']<>''){
		 header("location:admin.php");
		 exit();
		}
}

//检查用户是否登录
function loginout()
{
	if($_SESSION['username']=='' and $_SESSION['password']=='' and $_SESSION['id']=='' and $_SESSION['rankadmin']==''){
		 header("location:login.php");
		 exit();
		}
}
	
//获取用户退出登录
function exits()
{
	session_unset();
	session_destroy();
	header("location:login.php");
}

?>
